﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using Encoder = System.Drawing.Imaging.Encoder;

namespace Baby.Growup.Common
{
    public class ImageHelper
    {
        /// <summary>
        /// 图片压缩
        /// </summary>
        /// <param name="fileName">文件全路径</param>
        /// <param name="quality">质量压缩比</param>
        /// <param name="multiple">收缩倍数</param>
        /// <returns></returns>
        public static bool GetThumImage(string fileName, long quality, int multiple)
        {
            try
            {
                if (!File.Exists(fileName))
                {
                    return false;
                }

                long imageQuality = quality;
                Bitmap sourceImage = new Bitmap(fileName);
                ImageCodecInfo myImageCodecInfo = GetEncoderInfo("image/jpeg");
                Encoder myEncoder = Encoder.Quality;
                EncoderParameters myEncoderParameters = new EncoderParameters(1);
                EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, imageQuality);
                myEncoderParameters.Param[0] = myEncoderParameter;
                float xWidth = sourceImage.Width;
                float yWidth = sourceImage.Height;
                Bitmap newImage = new Bitmap((int) (xWidth/multiple), (int) (yWidth/multiple));
                Graphics g = Graphics.FromImage(newImage);

                g.DrawImage(sourceImage, 0, 0, xWidth/multiple, yWidth/multiple);
                g.Dispose();

                File.Delete(fileName);

                newImage.Save(fileName, myImageCodecInfo, myEncoderParameters);
                return true;
            }
            catch
            {
                return false;
            }
        }


        private static ImageCodecInfo GetEncoderInfo(String mimeType)
        {
            int j;
            var encoders = ImageCodecInfo.GetImageEncoders();
            for (j = 0; j < encoders.Length; ++j)
            {
                if (encoders[j].MimeType == mimeType)
                    return encoders[j];
            }
            return null;
        }
    }
}
